package com.ts.interceptor;

import com.ts.constant.JwtClaimsConstant;
import com.ts.context.BaseContext;
import com.ts.properties.JwtProperties;
import com.ts.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        // 首先检查是否是应该排除的路径
        if (isExcludedPath(requestURI)) {
            log.info("✅ 排除路径请求，直接放行: {}", requestURI);
            return true;
        }

        log.info("=== JWT拦截器处理: {} ===", requestURI);
        log.info("Handler类型: {}", handler.getClass().getSimpleName());

        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            log.info("✅ 非Controller方法，直接放行");
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        //2、校验令牌
        try {
            log.info("开始JWT校验");
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户id：{}", userId);

            BaseContext.setCurrentId(userId);
            log.info("✅ JWT校验通过");
            return true;
        } catch (Exception ex) {
            log.error("❌ JWT校验失败: {}", ex.getMessage());
            response.setStatus(401);
            return false;
        }
    }

    private boolean isExcludedPath(String uri) {
        return uri.startsWith("/swagger-ui") ||
                uri.startsWith("/webjars") ||
                uri.startsWith("/v3/api-docs") ||
                uri.startsWith("/swagger-resources") ||
                uri.equals("/doc.html") ||
                uri.equals("/user/login") ||
                uri.equals("/favicon.ico");
    }
}